import React, {Component} from 'react';
import {
    Addition,
    BigSpace,
    Conversion,
    HeaderContainer,
    HeaderLeftContainer,
    HeaderMiddleContainer,
    HeaderRightContainer,
    HeaderWrapper,
    LOGO,
    NavItem,
    SearchBox,
    SearchBoxWrapper,
    SearchInfoContainer,
    SearchInfoItem,
    SearchInfoList,
    SearchInfoTitle,
} from "./style";
import './style.css';
import {CSSTransition} from "react-transition-group";
import {connect} from "react-redux";
import store from "@/store";
import {actions} from './store'
import {actions as windowActions} from '@/common/window/store'
import {withRouter} from "react-router-dom";
import {errorMsg} from "@/util/global";
import {HomeOutlined, UserOutlined, AppstoreOutlined, MailOutlined, SoundOutlined} from '@ant-design/icons';
import {Avatar, Popover} from "antd";
import {getPath} from "@/util/routerUtil";
import EventBus from "@/util/EventBus";
import MinePopover from "@/common/header/MinePopover";
import Confirm from "@/common/Modal/Confirm";
import {clearUserInfo} from "@/util/UserUtil";
import {regainUserInfo} from "@/api/SysUserInfo";
import {toBase64} from "@/util/CodeUtils";
import {INIT_USER_INFO} from "@/store/common/user/type";
import LeftDrawer from "@/component/Drawer/LeftDrawer";
import Http from "@/util/http";


class Header extends Component {
    constructor(props) {
        super(props);
        this.PushToUploadGame = this.PushToUploadGame.bind(this);
        this.EventResolve = this.EventResolve.bind(this);
        this.PushToLogin = this.PushToLogin.bind(this);
        this.PushToMine = this.PushToMine.bind(this);
        this.PushToJoinUs = this.PushToJoinUs.bind(this);
        this.PushToHome = this.PushToHome.bind(this);
        this.LoginOut = this.LoginOut.bind(this);
        this.PushToUploadPage = this.PushToUploadPage.bind(this);
        this.handleClickSearchBtn = this.handleClickSearchBtn.bind(this);
        this.handleClickLoginOut = this.handleClickLoginOut.bind(this);
        this.renderUserElement = this.renderUserElement.bind(this);
        this.renderSearchBarElement = this.renderSearchBarElement.bind(this);
        this.addEventListen = this.addEventListen.bind(this);
        this.props.handleChangeRouter(window.location.pathname)
        /* 路由事件监听 */
        this.props.history.listen(location => {
            this.props.handleChangeRouter(location.pathname)
        })
        // 定义全局可以访问的Router
        window._ROUTER_ = this.props.history;
        this.state = {
            loginOutVisible: false
        }
    }

    componentDidMount() {
        /* 初始化热搜数据 */
        store.dispatch(actions.headerSearchInit());
        /* 处理全局刷新用户信息事件 */
        EventBus.addListener('RegainUserInfo', async () => {
            /* 实时更新 */
            await regainUserInfo()
                .then(response => {
                    if (response.data) {
                        this.props.regainUser(response.data);
                        sessionStorage.setItem('just-game-obj', toBase64(response.data));
                    }
                })
        });
    }

    componentWillUnmount() {
        /* 移除事件监听 */
        window.removeEventListener('click', this.EventResolve);
    }

    PushToUploadGame() {
        if (this.props.userInfo.id) {
            this.props.history.push('/upload-game');
        } else {
            errorMsg("请先登录再尝试！")
            this.PushToLogin();
        }
    }

    handleClickSearchBtn(e) {
        e.preventDefault();
        if (getPath() === '/search') {
            EventBus.emit('searchGames', this.props.searchValue)
        } else {
            this.props.history.push({pathname: '/search', query: {kw: this.props.searchValue}});
        }
        // 清空搜索框内容
        // this.props.handleClearInputSearch();
    }

    EventResolve(e) {
        if (!this.props.TopSearchFocused && !this.props.searchFocused) {
            this.props.handleClickTopSearchEvent(false);
            window.removeEventListener('click', this.EventResolve);
        }
    }

    addEventListen() {
        window.addEventListener('click', this.EventResolve, true)
    }

    PushToLogin() {
        this.props.history.push('/login');
    }

    PushToMine() {
        if (this.props.userInfo.id) {
            this.props.history.push('/mine/info');
        } else {
            errorMsg("请先登录再尝试！")
            this.PushToLogin();
        }
    }

    PushToUploadPage() {
        this.props.history.push('/page');
    }

    PushToJoinUs() {
        this.props.history.push('/login/sign');
    }

    PushToHome() {
        this.props.history.push('/home')
    }

    handleClickLoginOut(bool) {
        this.setState({logoutVisible: bool})
    }

    /**
     * 渲染用户组件对象
     */
    renderUserElement() {
        let userInfo = this.props.userInfo;
        if (userInfo.id) {
            /* 用户已登录 */
            return <>
                <NavItem className='mine'>
                    <AppstoreOutlined className={'icon'}/>
                    <MailOutlined className={'icon'}/>
                    <SoundOutlined className={'icon'}/>
                    {/* 用户登录后将鼠标放置在用户的名字上时会显示更多细节 */}
                    <Popover content={<MinePopover userInfo={userInfo} that={this}/>}
                             overlayStyle={{position: "fixed"}}
                             destroyTooltipOnHide={true}
                             placement={"bottom"}>
                        <Avatar
                            onClick={this.PushToMine}
                            style={{userSelect: "none",cursor:'pointer'}}
                            src={userInfo.images}>
                            {userInfo.onlineName}
                        </Avatar>
                    </Popover>
                </NavItem>
            </>
        } else {
            /* 用户未登录 */
            return <>
                <NavItem className='right'>
                    <UserOutlined style={{marginRight: '3px'}}/>
                    <a onClick={() => this.PushToLogin()}>登录</a>
                    <label>/</label>
                    <a onClick={() => this.PushToJoinUs()}>注册</a>
                </NavItem>
            </>
        }
    }


    renderSearchBarElement(minWidth) {
        if (this.props.width.split("px")[0] < minWidth) {
            return;
        }
        const {
            shouldTopSearchOpen,
            handleTopSearchFocus,
            handleClickConversion,
            TopSearchWords,
            searchFocused,
            handleSearchFocusEvent,
            searchValue,
            handleInputSearchInfo
        } = this.props
        return <SearchBoxWrapper>
            <CSSTransition
                timeout={1000 * 0.3}
                in={!!searchFocused}
                classNames="slide">
                {/* 头部搜索框 */}
                <SearchBox
                    headerNeedFixed={this.props.headerNeedFixed}
                    onChange={(e) => handleInputSearchInfo(e)}
                    value={searchValue}
                    onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                            this.handleClickSearchBtn(e)
                        }
                    }}
                    onFocus={() => {
                        handleSearchFocusEvent(true);
                        this.addEventListen();
                    }}
                    onBlur={(e) => {
                        handleSearchFocusEvent(false);
                    }}
                    className={searchFocused ? 'search-focus' : ''}/>
            </CSSTransition>
            {/* 搜索框右侧放大镜图标 */}
            <i className={searchFocused ? 'search-focus iconfont zoom' : 'iconfont zoom'}
               style={{color: this.props.headerNeedFixed ? 'rgba(0,0,0,0)' : 'rgba(0,0,0,1)'}}
               onMouseDown={this.handleClickSearchBtn}>&#xe605;</i>
            {/* 聚焦 */}
            <SearchInfoContainer className={shouldTopSearchOpen ? 'display' : 'hidden'}
                                 onMouseEnter={() => handleTopSearchFocus(true)}
                                 onMouseLeave={() => handleTopSearchFocus(false)}>
                <SearchInfoTitle>
                    热搜
                    <Conversion onClick={(e) => handleClickConversion(e.target)}>
                        <span style={{float: 'right'}}>换一批</span>
                        <i id="HeaderSwitch" className='iconfont spin'>&#xe629;</i>
                    </Conversion>
                </SearchInfoTitle>
                <SearchInfoList>
                    {
                        TopSearchWords.map((item, index) => {
                            return (
                                <SearchInfoItem key={index}>{item}</SearchInfoItem>
                            )
                        })
                    }
                </SearchInfoList>
            </SearchInfoContainer>
        </SearchBoxWrapper>
    }

    LoginOut() {
        clearUserInfo();
        this.props.handleChangeRouter('/home');
        window._ROUTER_.push("/home");
        this.handleClickLoginOut(false);
        Http.post('/sys/user/info/logout');
    }

    render() {
        /* 隐藏Header */
        if (!this.props.visible) {
            return null;
        }
        return (
            <>
                {/* 退出登录前弹出弹窗询问操作 */}
                <Confirm content={"您确定要退出登陆吗？"} titleText={"温馨提示"}
                         visible={this.state.logoutVisible} onOk={this.LoginOut}
                         onCancel={() => this.handleClickLoginOut(false)}/>
                <HeaderWrapper id={"Header"} style={{width: this.props.width}}
                               headerNeedFixed={this.props.headerNeedFixed}
                               isScrollToTop={this.props.isScrollToTop}
                >
                    <HeaderContainer>
                        {/* 顶栏左容器 */}
                        <HeaderLeftContainer>
                            {/* 左栏 */}
                            <LeftDrawer/>
                            {/* LOGO */}
                            <LOGO onClick={() => this.PushToHome()}/>
                        </HeaderLeftContainer>

                        {/* 顶栏右容器 */}
                        <HeaderRightContainer>
                            <Addition>
                                {/* 渲染用户区 */}
                                {this.renderUserElement()}
                            </Addition>
                        </HeaderRightContainer>

                        {/* 顶栏中间容器 */}
                        <HeaderMiddleContainer>
                            {/* 首页按钮 */}
                            {/*<NavItem className='left active'>*/}
                            {/*    <HomeOutlined onClick={this.PushToHome}/>*/}
                            {/*</NavItem>*/}
                            {/* 渲染搜索栏 */}
                            {this.renderSearchBarElement(768)}
                        </HeaderMiddleContainer>
                    </HeaderContainer>
                </HeaderWrapper>
                <BigSpace/>
            </>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        /*引入redux-immutable后写法*/
        width: state.getIn(['window', 'width']),
        visible: state.getIn(['header', 'visible']),
        searchValue: state.getIn(['header', 'searchValue']),
        searchFocused: state.getIn(['header', 'searchFocused']),
        TopSearchWords: state.getIn(['header', 'TopSearchWords']),
        TopSearchFocused: state.getIn(['header', 'TopSearchFocused']),
        shouldTopSearchOpen: state.getIn(['header', 'shouldTopSearchOpen']),
        isScrollToTop: state.getIn(['window', 'isScrollToTop']),
        headerNeedFixed: state.getIn(['window', 'headerNeedFixed']),
        userInfo: state.getIn(['user']).toJS(),
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        handleClickConversion(e) {
            let DOM = document.getElementById('HeaderSwitch');
            let originAngle = DOM.style.transform.replace(/[^0-9]/ig, '');
            if (originAngle) {
                originAngle = parseInt(originAngle, 10);
            } else {
                originAngle = 0;
            }
            DOM.style.transform = 'rotate( ' + (originAngle + 360) + 'deg )';
        },
        handleSearchFocusEvent(bool) {
            dispatch(actions.headerSearchFocused(bool));
            // if (bool)
            //     dispatch(actions.headerTopSearchOpen(true));
        },
        handleClearInputSearch() {
            dispatch(actions.headerSearchInput(''))
        },
        handleInputSearchInfo(e) {
            dispatch(actions.headerSearchInput(e.target.value))
        },
        handleTopSearchFocus(bool) {
            dispatch(actions.headerTopSearchFocused(bool))
        },
        handleClickTopSearchEvent(bool) {
            // dispatch(actions.headerTopSearchOpen(bool));
        },
        handleChangeRouter(val) {
            dispatch(windowActions.setWindowRouter(val));
        },
        regainUser(data) {
            let action = {
                type: INIT_USER_INFO,
                value: data
            };
            dispatch(action);
        }
    }

}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Header));
